package com.elontian.http.async2.handler;

import com.elontian.http.async2.modle.Response;
import com.elontian.http.async2.util.HttpParams;
import com.elontian.util.CheckUtil;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public abstract class AsyncHttpHandler {

	public abstract void succ(Response obj);

	public abstract void fail(Exception e);

	// *****************************

	public static final int SUCC = 1;
	public static final int FAIL = 2;
	private Handler handler;

	private String url;

	public void setUrl(String url) {
		this.url = url;
	}

	public AsyncHttpHandler() {
		// TODO Auto-generated constructor stub

		if (Looper.myLooper() != null) {
			handler = new Handler() {
				@Override
				public void dispatchMessage(Message msg) {
					// TODO Auto-generated method stub
					AsyncHttpHandler.this.dispatchMessage(msg);
				}
			};
		}

	}

	protected void dispatchMessage(Message msg) {
		// TODO Auto-generated method stub

		switch (msg.what) {
		case SUCC:
			Response result = (Response) msg.obj;
			String resUrl = (String) result.get(HttpParams.URL);
			if (CheckUtil.isNotNullString(resUrl) && resUrl.equals(url)) {
				succ(result);
			}

			break;
		case FAIL:
			fail((Exception) msg.obj);
			break;

		default:
			break;
		}
	}

	public void sendSuccMessage(Object r) {
		// TODO Auto-generated method stub
		Message msg = handler.obtainMessage();
		msg.what = SUCC;
		msg.obj = r;
		handler.sendMessage(msg);
	}

	public void sendFailMessage(Exception e) {
		// TODO Auto-generated method stub
		Message msg = handler.obtainMessage();
		msg.what = FAIL;
		msg.obj = e;
		handler.sendMessage(msg);
	}

}
